# -*- coding: utf-8 -*-
"""
Created on Wed Jul 13 14:35:25 2022

@author: LX
"""


import time
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import sys
from aip import AipSpeech
from xpinyin import Pinyin
import serial
from time import sleep
import pyaudio
import wave
from PyQt5.QtGui import QPixmap

APP_ID = '26618988'#请填写你的APP_ID 
API_KEY = 'cZPEkGknPuk1yAOZ99yNePTg'#请填写你的API_KEY 
SECRET_KEY = 'i474ccLuKWkwz02WcSOfjyy5fpi725YY'#请填写你的SECRET_KEY 
client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)

#调用百度云api            
def get_text(wav_bytes):
    result = client.asr(wav_bytes, 'wav', 16000, {'dev_pid': 1537,})
    try:
        text = result['result'][0]
    except Exception as e:
        print(e)
        text = ""
    return text

def get_file_content(filePath):
    with open(filePath, 'rb') as fp:
        return fp.read()
def luying():
    CHUNK = 1024
    FORMAT = pyaudio.paInt16
    CHANNELS = 1
    RATE = 16000
    RECORD_SECONDS = 5
    WAVE_OUTPUT_FILENAME = "output.wav"
    frames = [] 
    p = pyaudio.PyAudio()
    stream = p.open(format=FORMAT,
                    channels=CHANNELS,
                    rate=RATE,
                    input=True,
                    frames_per_buffer=CHUNK)
    print("请说话...")
    for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
        data = stream.read(CHUNK)
        frames.append(data)
    stream.stop_stream()
    stream.close()
    p.terminate()
    wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
    wf.setnchannels(CHANNELS)
    wf.setsampwidth(p.get_sample_size(FORMAT))
    wf.setframerate(RATE)
    wf.writeframes(b''.join(frames))
    wf.close()
    
def shibeixianshi():
    print("\n正在分析...")
    text = get_text(get_file_content('output.wav'))
    print(text)
    p = Pinyin()
    result_1 = p.get_pinyin(text)
    print (result_1)
    
    result2 = p.get_pinyin(text, tone_marks='marks')
    print(result2)
    s = result2.split('-')
    result3 = ' '.join(s[0:])
    print(result3)
    
    str_list = result_1.split(sep='-')
    print (str_list)
    str_z = ''
    for str_l in str_list:
        for str_l1 in str_l:
            print (str_l1)
            if (str_l1.isalpha()):
                str_z += str_l1
    print (str_z)
    serial.write((str_z).encode("gbk"))
    sleep(0.1)
    return (text,result3)




class MyWindow(QWidget):
    # 声明一个信号 只能放在函数的外面
    my_signal = pyqtSignal(str)

    def __init__(self):
        super().__init__()
        self.init_ui()
        self.msg_history = list()  # 用来存放消息

    def init_ui(self):
        self.resize(1024, 800)
        self.setWindowTitle("盲文辅助交流书写系统")

        # 创建一个整体布局器
        container = QVBoxLayout()

        # 用来显示检测到漏洞的信息
        self.msg = QLabel("")
        self.msg.resize(600, 15)
        print(self.msg.frameSize())
        self.msg.setWordWrap(True)  # 自动换行
        self.msg.setAlignment(Qt.AlignTop)  # 靠上
        #self.msg.setStyleSheet("background-color: yellow; color: black;")

        # 创建一个滚动对象
        scroll = QScrollArea()
        scroll.setWidget(self.msg)

        # 创建垂直布局器，用来添加自动滚动条
        v_layout = QVBoxLayout()
        pixmap = QPixmap("22.png")
        label = QLabel(self)
        label.setPixmap(pixmap)
        #v_layout.setGeometry(100, 300, 200, 200)
        container.addWidget(label)
        v_layout.addWidget(scroll)
        #v_layout.addWidget(label)
        
        # 创建水平布局器
        h_layout = QHBoxLayout()
        v_layout.addWidget(scroll)
        btn_0 = QPushButton("开始", self)
        btn_1 = QPushButton("关闭", self)
        # 绑定按钮的点击，点击按钮则开始检测
        btn_0.setGeometry(100, 480, 372, 260)
        btn_1.setGeometry(572, 480, 372, 260)
        btn_0.clicked.connect(self.click_my_btn)
        btn_1.clicked.connect(self.click_gb_btn)
       # h_layout.addStretch()  # 伸缩器but放中间
        #h_layout.addWidget(btn_0)
       # h_layout.addStretch()
       # h_layout.addWidget(btn_1)
       # h_layout.addStretch()

        # 操作将要显示的控件以及子布局器添加到container
        #container.addLayout(h_layout)
        container.addLayout(h_layout)
        container.addLayout(v_layout)
        #v_layout.addLayout(h_layout)

        # 设置布局器
        self.setLayout(container)
        

        # 绑定信号和槽
        self.my_signal.connect(self.my_slot)

    def my_slot(self, msg):
        # 更新内容
        print(msg)
        self.msg_history.append(msg)
        self.msg.setText("<br>".join(self.msg_history))
        self.msg.resize(660, self.msg.frameSize().height() + 15)
        self.msg.repaint()  # 更新内容，如果不更新可能没有显示新内容
       
        
    def click_gb_btn(self,arg):
        serial.close()
        w.close()
        
    def click_my_btn(self, arg):
        # 槽函数，点击按钮则调用该函数
        # 这里的参数正好是信号发出，传递的参数
        # print("点击按钮啦~", arg)
        msg = '请说话：'
        self.my_signal.emit(msg)
        luying()
        msg = '正在分析...'
        self.my_signal.emit(msg)
        ms = shibeixianshi()#调用录音识别串口输出函数 
        print (ms)
        for msg in ms:
            self.my_signal.emit(msg)
        
        
        
if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = MyWindow()
    w.show()
    serial = serial.Serial('/dev/ttyUSB0',115200, timeout=0.5)
    app.exec()
